package minuy.android.slowcarremotecontrol.service;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import minuy.android.slowcarremotecontrol.MainActivity;
import minuy.android.slowcarremotecontrol.tool.BluetoothUtils;
import minuy.android.slowcarremotecontrol.tool.Constant;
import minuy.android.slowcarremotecontrol.tool.HanderHelper;

public class BluetoothService  {
    private static BluetoothService bluetoothService;
    HanderHelper handerHelper;
    BluetoothUtils bluetoothUtils;
    private BluetoothService(){
        handerHelper = HanderHelper.getHanderHelper();

    }
    static public BluetoothService getBluetoothService(){
        if(bluetoothService==null){
            bluetoothService = new BluetoothService();
        }
        return bluetoothService;
    }
    //连接蓝牙
    public void BluetoothLink(MainActivity mainActivity) {
        if(!bluetoothUtils.getBluetoothStatus()){
            bluetoothUtils.openBluetooth();
        }
        bluetoothUtils.showPairedDevices(mainActivity);
    }

    public void send(String obj) {
        if(bluetoothUtils.getConnectStatus()) {
            bluetoothUtils.send(obj);
        }
    }

    public void Init(Context context){
        bluetoothUtils = new BluetoothUtils(context);
        //初始化资源
        bluetoothUtils.init();
        bluetoothUtils.connectChange(new BluetoothUtils.ConnectStateChange() {
            @Override
            public void onConnectSuccess(BluetoothDevice device) {
                //蓝牙已连接
                handerHelper.sendHanderMsg(Constant.BLUETOOTH_CONNECTED);
            }

            @Override
            public void onConnectFailed(String msg) {
                handerHelper.sendHanderMsg(Constant.BLUETOOTH_CONNECTION_FAIL,msg);
            }

            @Override
            public void newConnect(BluetoothDevice device) {
                handerHelper.sendHanderMsg(Constant.BLUETOOTH_NEW_CONNECTION,device);
            }

            @Override
            public void onDisConnect() {
                handerHelper.sendHanderMsg(Constant.BLUETOOTH_DISCONNECTION);
            }
        });

        bluetoothUtils.onReceiveBytes(new BluetoothUtils.ReceiveBytes() {
            @Override
            public void onReceiveBytes(byte[] bytes) {
                handerHelper.sendHanderMsg(Constant.BLUETOOTH_RECEIVE_MSG,bytes);
            }
        });
    }

    //释放资源
    public void Close(){
        bluetoothUtils.onDestory();
    }
}
